/* ---------------------------------------------------------------------------------------------
 *
 *            Capital Alliance Software Confidential Proprietary
 *            (c) Copyright CAS 201{x}, All Rights Reserved
 *                          www.pekall.com
 *
 * ----------------------------------------------------------------------------------------------
 */

package com.pekall.myDictionary.utils;

public class ChineseCompare {

    private String ENCODE = "UTF-16";

    private String SERVER_ENCODE = "gbk";

    public int compare(String s1, String s2)

    {
        String m_s1 = null, m_s2 = null;
        try {
            m_s1 = new String(s1.getBytes(SERVER_ENCODE), ENCODE);
            m_s2 = new String(s2.getBytes(SERVER_ENCODE), ENCODE);
        } catch (Exception ex) {
            return s1.compareTo(s2);
        }
        int res = chineseCompareTo(m_s1, m_s2);
        return res;
    }

    @SuppressWarnings("null")
    public int getCharCode(String s) {
        if (s == null && s.equals(""))
            return -1;
        byte[] b = s.getBytes();
        int value = 0;
        for (int i = 0; i < b.length && i <= 2; i++) {
            value = value * 100 + b[i];
        }
        return value;
    }

    public int chineseCompareTo(String s1, String s2) {
        int len1 = s1.length();
        int len2 = s2.length();
        int n = Math.min(len1, len2);
        for (int i = 0; i < n; i++) {
            int s1_code = getCharCode(s1.charAt(i) + "");
            int s2_code = getCharCode(s2.charAt(i) + "");
            if (s1_code != s2_code)
                return s1_code - s2_code;
        }
        return len1 - len2;
    }
}
